import store from '../index.js'
import { apiGet, apiPost, CTS } from '../../utils/http'
import { MessageBox } from 'element-ui'
import { resetRouter } from '../../router';
import router from '../../router';
import { filterAsyncRoutes } from './permission';


/*
* id        用户id
* username  用户姓名
* nickname  用户昵称
* roles     用户角色
* token     token
* permissions 许可
* */
const user = {
  id: 0,
  token: '',
  roles: [],
  userId: 0,
  username: '',
  nickname: '',
  email: '',
  mobile: '',
  status: 0,
  createUserId: 0,
  createTime: 0,
  deptId: 0,
  customId: '',
  remark: ''
}

const state = {
  ...user
}

const mutations = {
  /*
  * 修改用户信息
  * */
  setUserInfo(state, options) {
    for (let key in options) {
      let o = { ['user/' + key]: options[key] }
      store.commit('setStateData', o)
    }
  },
  /*
  * 清除用户信息
  * */
  clearUserInfo(state) {
    for (let key in state) {
      // 还原为默认数据
      let o = { ['user/' + key]: user[key] }
      store.commit('setStateData', o)
    }
  },
}

const actions = {
  /*
  * 登录
  * */
  login({ state }) {
    return new Promise(async (resolve) => {
      sessionStorage.setItem('login_time', Date.now())
      // 重置路由
      resetRouter()
      // 根据角色添加路由
      const accessRoutes = await store.dispatch('permission/generateRoutes', state.roles)
      accessRoutes.forEach(m => {
        router.addRoute(m)
      })
      resolve()
    })
  },
  // 退出登录
  logout({ commit }) {
    resetRouter()

    store.commit('tagsView/DEL_ALL_VISITED_VIEWS')
    store.commit('tagsView/DEL_ALL_CACHED_VIEWS')
    commit('clearUserInfo')
  },
  // 动态修改权限
  // async changeRoles({ commit, dispatch }, role) {
  //   const token = role + '-token'
  //
  //   commit('SET_TOKEN', token)
  //   setToken(token)
  //
  //   const { roles } = await dispatch('getInfo')
  //
  //   resetRouter()
  //
  //   // generate accessible routes map based on roles
  //   const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
  //   // dynamically add accessible routes
  //   router.addRoutes(accessRoutes)
  //
  //   // reset visited views and cached views
  //   dispatch('tagsView/delAllViews', null, { root: true })
  // },
  /**
   * 更新用户信息，并判断登陆是否正常
   * */
  updateUserInfo({ commit }) {
    return new Promise((resolve, reject) => {
      apiGet('/sso/user', {}).then(res => {
        if (res.ok) {
          res.data.roles = ['admin']
          commit('setUserInfo', res.data)
          resolve(res)
        }
        else {
          reject(res)
        }
      }).catch((err) => {
        reject(err)
        console.log(err)
      })
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
